package rjeutsky.database.jpa.models;

import java.util.LinkedList;
import java.util.List;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import javax.persistence.Transient;

import org.hibernate.Session;

import rjeutsky.models.Publication;

@Entity
@Table(name="Publication")
public class JPAPublication {
	private long id;
	private String name;
	private long price;
	private List<JPASubscription> subscriptions;
	
	@Id
	@GeneratedValue(strategy=GenerationType.IDENTITY)
	public long getId() {
		return id;
	}
	public void setId(long id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public long getPrice() {
		return price;
	}
	public void setPrice(long price) {
		this.price = price;
	}
	
	@ManyToMany
	@JoinTable(name="PublicationSubscription", 
	joinColumns={@JoinColumn(name="publicationId")},
	inverseJoinColumns={@JoinColumn(name="subscriptionId")})
	public List<JPASubscription> getSubscriptions() {
		return subscriptions;
	}
	public void setSubscriptions(List<JPASubscription> subscriptions) {
		this.subscriptions = subscriptions;
	}
	
	@Transient
	public Publication getPublication() {
		Publication publication = new Publication();
		publication.setId(id);
		publication.setName(name);
		publication.setPrice(price);
		return publication;
	}

	@Transient
	public static JPAPublication getJPAPublication(Session session, Publication publication) {
		if (publication == null) {
			return null;
		}
		
		return (JPAPublication) session.get(JPAPublication.class, publication.getId());
	}
	
	@Transient
	public static List<Publication> getPublications(List<JPAPublication> jpaPublications) {
		List<Publication> publications = new LinkedList<Publication>();
		if (jpaPublications != null) {
			for (JPAPublication Publication : jpaPublications) {
				publications.add(Publication.getPublication());
			}
		}
		
		return publications;
	}
}
